/*
 * @Descripttion: 
 * @version: 
 * @Author: ada.wu
 * @Date: 2023-10-19 16:02:52
 * @LastEditors: ada.wu
 * @LastEditTime: 2024-04-10 10:08:02
 */
import axios from "axios";
import { showToast } from 'vant'
import router from '../router'
import storageUtil from "./storageUtil";
import { getHostWxMpAppId, getPathWxMpAppId } from "/@/util/index";


const service = axios.create({
    timeout: 600 * 1000,
    withCredentials: true,
});

service.interceptors.request.use(
    (config) => {
        if (import.meta.env.VITE_APP_SYSTEM_CODE) {
            config.headers.systemCode = import.meta.env.VITE_APP_SYSTEM_CODE
        }

        if (storageUtil.getSystemCode()) {
            config.headers.systemCode = storageUtil.getSystemCode()
            config.headers['x-system-code'] = storageUtil.getSystemCode()
        }
        if (storageUtil.getImagetalkingid()) {
            config.headers.imagetalkingid = storageUtil.getImagetalkingid()
        }
        if (storageUtil.getCustomerAuthorization()) {
            config.headers.authorization = storageUtil.getCustomerAuthorization()
        }

        config.headers.WxMpAppId = getPathWxMpAppId() || getHostWxMpAppId()
        config.headers.CouponDomain = window.location.host

        //兼容上下文
        if (config.url?.indexOf('/customer') === 0) {
            config.url = import.meta.env.VITE_APP_BASE_API + config.url
        }
        // console.log(config.url, '请求地址');
        // console.log('config.data==', config.data)






        if (config.data) {

            if (storageUtil.getSystemCode() && !config.data.systemCode) {
                config.data.systemCode = storageUtil.getSystemCode()
            }
        }
        console.log('config====', config)
        if (config && typeof config.data !== 'undefined') {
            if (Object.keys(config.data).includes("TYPE") && config.data.TYPE === 'FORM') {
                let fm = new FormData();
                Object.keys(config.data).forEach(key => {
                    fm.append(key, config.data[key]);
                })
                config.data = fm;
            }
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

service.interceptors.response.use(
    (response: any) => {
        // console.error('response.config===', response)
        // const token = response.headers.authorization
        // if (token) {
        //     storageUtil.setToken(token)
        // }
        // console.log(response.headers)
        const { authorization, imagetalkingid } = response.headers
        if (response.config.url.indexOf("/getImgCodeBase64") > 0) {
            storageUtil.setImagetalkingid(imagetalkingid)
        }

        if (authorization) {
            storageUtil.setCustomerAuthorization(authorization)
        }
        let data = response.data;

        if (response.config.returnRaw) {
            return Promise.resolve(data)
        }

        const errCode = data ? data.state : null
        if ([undefined, null, 0].includes(errCode)) {
            return Promise.resolve(data.result)
        }
        if (data.msg === '请登录') {
            // console.log('login======11111111')
            storageUtil.removeCustomerAuthorization()
            router.push({
                path: '/login', query: {
                    callbackUrl: window.location.href
                }
            }).then()
            showToast('未登录')
            return
        }
        if (data.success == false) {
            if (data.msg || data.result) {
                setTimeout(() => {
                    showToast(data.msg || data.result)
                }, 100)

            }
        }

        return Promise.reject(data)
    },
    (error) => {
        // if (error.response.status === 401) {
        //     storageUtil.removeCustomerAuthorization()
        //     router.push({
        //         path: '/login', query: {
        //             callbackUrl: window.location.href
        //         }
        //     }).then()
        //     showToast('未登录')
        //     return
        // }
        showToast(`网络错误: ${error.message}`)
        return Promise.reject(error);
    }
);

export default service;
